export default {
  namespaced: true,
  state() {
    return {
      cart: JSON.parse(uni.getStorageSync('cart') || '[]')
    }
  },
  mutations: {
    addtoCart(state, goods) {
      const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
            
      if(!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }   
      this.commit('m_cart/savetoStorage')
    },
    savetoStorage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    updateGoodsState(state, goods) {
      const res = state.cart.find( i => i.goods_id === goods.goods_id)
      if(res) {
        res.goods_state = goods.goods_state
        
        this.commit('m_cart/savetoStorage')
      }
    },
    updateGoodsCount(state, goods) {
      const res = state.cart.find( i => i.goods_id === goods.goods_id)
      if(res) {
        res.goods_count = goods.goods_count
        
        this.commit('m_cart/savetoStorage')
      }
    },
    removeGoodsById(state, goods_id) {
      state.cart = state.cart.filter(i => i.goods_id !== goods_id )
      
      this.commit('m_cart/savetoStorage')
    },
    updateAllGoodsState(state, newState) {
      state.cart.forEach(i => i.goods_state = newState)
      
      this.commit('m_cart/savetoStorage')
    }
  },
  actions: {
    
  },
  getters: {
    total(state) {
      // let c = 0
      // state.cart.forEach(item => c += item.goods_count)
      // return c
      return state.cart.reduce((total, item) => total += item.goods_count, 0)
    },
    totalCount(state) {
      return state.cart.filter( i => i.goods_state).reduce((total, item) =>  total += item.goods_count, 0)
    },
    totalPrice(state) {
      return state.cart.filter( i => i.goods_state).reduce((total, item) =>  total += item.goods_count * item.goods_price, 0)
    }
  }
  
}